package com.whfp.afs330h_sdk.utils;

import android.content.Context;
import android.text.TextUtils;
import android.util.Log;


import com.blankj.utilcode.util.EncodeUtils;
import com.clj.fastble.BleManager;
import com.clj.fastble.callback.BleMtuChangedCallback;
import com.clj.fastble.callback.BleNotifyCallback;
import com.clj.fastble.callback.BleWriteCallback;
import com.clj.fastble.data.BleDevice;
import com.clj.fastble.exception.BleException;
import com.whfp.afs330h_sdk.R;
import com.whfp.afs330h_sdk.bean.AFS330H_DeviceStatusBean;
import com.whfp.afs330h_sdk.callback.ConnectCallback;
import com.whfp.afs330h_sdk.callback.DeviceCallback;

import java.util.List;

public class DeviceUtils {

    //设备类型，默认为0  0:破冰2号  1:破冰二合一
    private int deviceType = 0;

    //ASF330H设备工具类
    private AFS330H_XY_bean afh330HXyBean;
    //上一个接收到的指令是
    private String previous_receive = "";
    //用于保存读取ID卡返回的JSON
    private String JSON_ID_CARD = "";
    //用于保存读取ID卡返回的JSON的字节长度
    private int JSON_ID_CARD_LENGTH = 0;
    //用于保存读取ID卡返回的信息校验和
    private String JSON_ID_CARD_CR = "";

    //用于保存毒品检测返回的JSON
    private String JSON_DPJC = "";
    //用于保存毒品检测返回的JSON的字节长度
    private int JSON_DPJC_LENGTH = 0;
    //用于保存毒品检测返回的信息校验和
    private String JSON_DPJC_CR = "";


    private String codeString = "";

    /**
     * 状态值
     */
    private boolean isXMDQ = false;    //项目读取是否成功
    private boolean isXMSC = false;   //项目删除是否成功
    private boolean isXMJZ = false;    //云端项目加载是否成功
    private boolean isDPJC = false;    //毒品检测是否成功

    /**
     * 错误码定义
     */
    private static int ERROR_CODE_KHDMBPP = 20201;  //客户代码不匹配
    private static int ERROR_CODE_WPPXMK = 20202;   //未匹配项目卡
    private static int ERROR_CODE_WCRJCSJK = 20203; //未插入检测试剂卡
    private static int ERROR_CODE_SBWLJ = 20204;    //设备未连接
    private static int ERROR_CODE_KHDMCW = 20205;   //客户代码错误
    private static int ERROR_CODE_SJTMBZQ = 20206;  //试剂条码不正确
    private static int ERROR_CODE_RZCW = 20207;     //认证错误
    private static int ERROR_CODE_CONNECT = 20208;  //设备连接错误
    private static int ERROR_CODE_IDKDQSB = 20209;  //ID卡读取失败
    private static int ERROR_CODE_XMJYCW = 20210;   //读取ID卡项目校验错误
    private static int ERROR_CODE_IDKWCR = 20211;   //ID卡未插入
    private static int ERROR_CODE_SJCDCW = 20212;   //数据长度错误
    private static int ERROR_CODE_WZDPPXMK = 20213; //未找到匹配项目卡
    private static int ERROR_CODE_XMKSJCW = 20214;  //项目卡数据错误
    private static int ERROR_CODE_OTHER = 20300;    //未知错误

    private Context context;
    private static DeviceUtils deviceUtils;

    public static DeviceUtils getInstance(Context c) {
        if (deviceUtils == null) {
            deviceUtils = new DeviceUtils();
            deviceUtils.context = c;
        }
        return deviceUtils;
    }


    public AFS330H_XY_bean getAfh330HXyBean() {
        if (afh330HXyBean == null) {
            afh330HXyBean = new AFS330H_XY_bean();
        }
        return afh330HXyBean;
    }


    /**
     * 设备操作类回调
     */
    private DeviceCallback deviceCallback;


    /**
     * 连接设备
     *
     * @param mac             出入的扫描的设备的二维码内容
     * @param connectCallback 回调事件
     */
    public void connectDevice(final String mac, ConnectCallback connectCallback) {
        String address = AESUtils.decryptDeviceMacByPB_2(mac);
        if (!TextUtils.isEmpty(address)) {
            deviceType = 0;
            BleManager.getInstance().connect(address, connectCallback);
        } else {
            connectCallback.onError(ERROR_CODE_CONNECT, context.getString(R.string.error_ewmbhg));
        }
    }

    /**
     * 连接设备（传递过来的就是解析好的MAC地址，此方法不对传入的MAC地址做解析，直接连接）
     *
     * @param mac             传入的MAC地址
     * @param deviceType      设备类型
     * @param connectCallback 回调事件
     */
    public void connectDeviceNoParsing(final String mac, final int deviceType, ConnectCallback connectCallback) {
        if (!TextUtils.isEmpty(mac)&&RxUtils.isMac(mac.trim())) {
            this.deviceType = deviceType;
            BleManager.getInstance().connect(mac.trim(), connectCallback);
        } else {
            connectCallback.onError(ERROR_CODE_CONNECT, context.getString(R.string.error_ewmbhg));
        }
    }

    /**
     * 连接设备（传递过来的就是解析好的MAC地址，此方法不对传入的MAC地址做解析，直接连接）
     *
     * @param mac             传入的MAC地址
     * @param refType         设备型号
     * @param connectCallback
     */
    public void connectDeviceNoParsing(final String mac, final String refType, ConnectCallback connectCallback) {
        if (!TextUtils.isEmpty(mac)) {
            //设置设备类型
            switch (refType) {
                case RxConstants.DEVICE_TYPE_PB2:
                    this.deviceType = 0;
                    break;
                case RxConstants.DEVICE_TYPE_PBEHY:
                case RxConstants.DEVICE_TYPE_PBEHY_YG:
                case RxConstants.DEVICE_TYPE_PBEHY_JTJ:
                    this.deviceType = 1;
                    break;
            }
            //开始连接
            BleManager.getInstance().connect(mac, connectCallback);
        } else {
            connectCallback.onError(ERROR_CODE_CONNECT, context.getString(R.string.error_ewmbhg));
        }
    }

    /**
     * 判断当前是有设备连接，如果有就返回当前已连接设备，没有就返回null
     */
    public BleDevice getCurrentDevice() {
        List<BleDevice> bleDevices = BleManager.getInstance().getAllConnectedDevice();
        if (bleDevices != null && bleDevices.size() > 0) {
            return bleDevices.get(0);
        } else {
            return null;
        }
    }

    /**
     * 订阅通知
     *
     * @param bleDevice                要订阅的设备对象
     * @param serviceUUID              服务的UUID
     * @param characteristicNotifyUUID 特征的UUID
     */
    private void notify(BleDevice bleDevice, String serviceUUID, String characteristicNotifyUUID) {
        BleManager.getInstance().notify(bleDevice, serviceUUID, characteristicNotifyUUID, new BleNotifyCallback() {
            @Override
            public void onNotifySuccess() {
                try {
                    String code = RxHexTool.intToHex(AESUtils.getAfs330hClientCode());
                    String codeToHex = RxHexTool.rightFillMethod(code, 2);
//                            Log.e("TAG", "客户代码转换后：" + codeToHex);
                    if (RxHexTool.hexStringBitNumbre(codeToHex) == 2) {
                        getAfh330HXyBean().setKhdm_d(codeToHex.substring(0, 2));
                        getAfh330HXyBean().setKhdm_g(codeToHex.substring(2, 4));
                        //发送获取设备信息指令（协议要求，如果不发送这条,发送任何指令都不会返回数据）
                        sendData(bleDevice, RxHexTool.rightFillMethodSumBleData(getAfh330HXyBean().getInstruction1()));
                    } else {
                        deviceCallback.onDeviceError(ERROR_CODE_KHDMCW, context.getString(R.string.error_khdmyw), "");
                        return;
                    }
                } catch (Exception e) {
                    deviceCallback.onDeviceError(ERROR_CODE_KHDMCW, context.getString(R.string.error_khdmyw), "");
                    return;
                }
                deviceCallback.notifySuccess();
            }

            @Override
            public void onNotifyFailure(BleException exception) {
                deviceCallback.notifyFailure(exception);
            }

            @Override
            public void onCharacteristicChanged(byte[] dataByte) {
                // 打开通知后，设备发过来的数据将在这里出现
                String data = RxHexTool.formatHexString(dataByte);
//                        Log.i("TAG", "未做任何处理：" + data);
                Log.i("TAG", "计算出来的校验位：" + RxHexTool.makeCheckSum(data.substring(0, data.length() - 2)));
                if (data.length() / 2 == 20 && data.substring(38, 40).equals(RxHexTool.makeCheckSum(data.substring(0, data.length() - 2)))) {//正常收发的指令数据
                    String ca = data.substring(0, 6);
//                            Log.i("TAG", "截取的前6个字符串为：" + ca);
                    previous_receive = ca;
                    String RS = data.substring(6, 8);
                    switch (ca) {
                        case AFS330H_XY_bean.instruction1://获取设备信息
                            if (RS.equals(AFS330H_XY_bean.DB_KHDMBPP)) {//客户代码不匹配
                                deviceCallback.onDeviceError(ERROR_CODE_KHDMBPP, context.getString(R.string.error_khdmbpp), "");
                            }
                            break;
                        case AFS330H_XY_bean.instruction2://获取设备状态
                            String BV = data.substring(8, 10);
                            String CC = data.substring(10, 12);
                            String IC = data.substring(12, 14);
                            int bv = (int) Long.parseLong(BV, 16); //电量百分比，转为10进制
                            AFS330H_DeviceStatusBean bean = new AFS330H_DeviceStatusBean(RS, bv, CC, IC);
                            deviceCallback.onDeviceStatus(bean);
                            break;
                        case AFS330H_XY_bean.instruction3://读取ID卡
                            //先清空上次读取的ID卡的信息JSON
                            JSON_ID_CARD = "";
                            if (RS.equals(AFS330H_XY_bean.DB_IDKDQCG) || RS.equals(AFS330H_XY_bean.DB_IDKDQ_WCR)) {//ID卡读取成功或者未插入ID卡
                                //改变项目读取状态
                                isXMDQ = true;

                                String PH = data.substring(8, 10);   //ID卡信息长度高位
                                String PL = data.substring(10, 12);  //ID卡信息长度低位
                                JSON_ID_CARD_CR = data.substring(12, 14);  //返回数据检验位

//                                        Log.i("TAG", "PH：" + PH + "PL:" + PL);
                                //转为10进制后计算
                                int ph = (int) Long.parseLong(PH, 16) * 0x100;
                                int pl = (int) Long.parseLong(PL, 16);

//                                        Log.i("TAG", "    111   :" + RxHexTool.hexToDecimal(PH) + "222222   :" + ph + "     333333333333333    ：" + pl + "  44444444    " + PL);
                                //获取将要返回的JSON信息的字节长度
                                JSON_ID_CARD_LENGTH = ph + pl;
//                        JSON_ID_CARD_LENGTH = RxHexTool.covert(String.valueOf(ph * 100)) + RxHexTool.covert(PL); // PH * 0x100 + PL JSON格式数据字节长度
//                                        Log.i("TAG", "计算出来读取ID将要返回的JSON信息的字节长度：" + JSON_ID_CARD_LENGTH);
//                                    } else if (RS.equals(AFS330H_XY_bean.DB_IDKDQ_WCR)) {//ID未插入
//                                        deviceCallback.onDeviceError(ERROR_CODE_IDKWCR, context.getString(R.string.error_idkwcr));
                            } else if (RS.equals(AFS330H_XY_bean.DB_XMJYCW)) {//项目校验错误
                                deviceCallback.onDeviceError(ERROR_CODE_XMJYCW, context.getString(R.string.error_xmjycw), "");
                            } else if (RS.equals(AFS330H_XY_bean.DB_IDKDQSB)) {//id卡读取失败
                                deviceCallback.onDeviceError(ERROR_CODE_IDKDQSB, context.getString(R.string.error_idkdqsb), "");
                            } else {
                                deviceCallback.onDeviceError(ERROR_CODE_OTHER, context.getString(R.string.error_wzcw), "");
                            }
                            break;
                        case AFS330H_XY_bean.instruction4://毒品检测
                            //先清空上次测试结果信息JSON
                            JSON_DPJC = "";
                            String PP = data.substring(8, 10);   //是否匹配项目卡
                            String PH = data.substring(10, 12);  //测试结果信息长度高位
                            String PL = data.substring(12, 14);  //测试结果信息查毒低位
                            JSON_DPJC_CR = data.substring(14, 16);  //返回数据校验位

                            if (RS.equals(AFS330H_XY_bean.DB_WCK)) {
                                deviceCallback.onDeviceError(ERROR_CODE_WCRJCSJK, context.getString(R.string.error_wcrjcsjk), "");
                            } else {
                                if (PP.equals(AFS330H_XY_bean.DB_YPPXMK)) {//已匹配项目卡
                                    //改变毒品检测状态
                                    isDPJC = true;
                                    //转为10进制后计算
                                    int ph = (int) Long.parseLong(PH, 16) * 0x100;
                                    int pl = (int) Long.parseLong(PL, 16);
                                    //获取将要返回的JSON信息的字节长度
                                    JSON_DPJC_LENGTH = ph + pl;
//                                            Log.i("TAG", "计算出来毒品检测将要返回的JSON信息的字节长度：" + JSON_DPJC_LENGTH);
                                } else if (PP.equals(AFS330H_XY_bean.DB_XMKSJCW)) {
                                    deviceCallback.onDeviceError(ERROR_CODE_XMKSJCW, context.getString(R.string.error_xmsjcw), "");
                                } else {
                                    deviceCallback.onDeviceError(ERROR_CODE_WPPXMK, context.getString(R.string.error_wppxmk), codeString);
                                }
                            }
                            break;
                        case AFS330H_XY_bean.instruction5://加载ID卡
//                                    Log.i("TAG", "加载ID卡收到反馈数据:" + data);
                            if (RS.equals(AFS330H_XY_bean.DB_IDKDQCG)) {//加载成功
                                //改变加载项目状态
                                isXMJZ = true;
//                                        Log.i("TAG", "已删除匹配项目卡");
                                //先清空上次读取的ID卡的信息JSON
                                JSON_ID_CARD = "";
                                String PH2 = data.substring(8, 10);   //ID卡信息长度高位
                                String PL2 = data.substring(10, 12);  //ID卡信息长度低位
                                JSON_ID_CARD_CR = data.substring(12, 14);  //返回数据检验位

//                                        Log.i("TAG", "PH：" + PH + "PL:" + PL);
                                //转为10进制后计算
                                int ph = (int) Long.parseLong(PH2, 16) * 0x100;
                                int pl = (int) Long.parseLong(PL2, 16);

//                                        Log.i("TAG", "    111   :" + RxHexTool.hexToDecimal(PH) + "222222   :" + ph + "     333333333333333    ：" + pl + "  44444444    " + PL);
                                //获取将要返回的JSON信息的字节长度
                                JSON_ID_CARD_LENGTH = ph + pl;
                            } else if (RS.equals(AFS330H_XY_bean.DB_IDKDQSB)) {//加载失败
                                deviceCallback.onDeviceError(ERROR_CODE_IDKDQSB, context.getString(R.string.error_idkdqsb), "");
                            } else if (RS.equals(AFS330H_XY_bean.DB_XMJYCW)) {//项目校验错误
                                deviceCallback.onDeviceError(ERROR_CODE_XMJYCW, context.getString(R.string.error_xmjycw), "");
                            } else if (RS.equals(AFS330H_XY_bean.DB_SJCDCW)) {//数据长度错误
                                deviceCallback.onDeviceError(ERROR_CODE_SJCDCW, context.getString(R.string.error_sjcdcw), "");
                            } else {
                                deviceCallback.onDeviceError(ERROR_CODE_OTHER, context.getString(R.string.error_wzcw), "");
                            }
                            break;
                        case AFS330H_XY_bean.instruction6://删除项目
                            if (RS.equals(AFS330H_XY_bean.DB_YSCPPXMK)) {
                                //改变删除项目状态
                                isXMSC = true;
//                                        Log.i("TAG", "已删除匹配项目卡");
                                //先清空上次读取的ID卡的信息JSON
                                JSON_ID_CARD = "";
                                String PH2 = data.substring(8, 10);   //ID卡信息长度高位
                                String PL2 = data.substring(10, 12);  //ID卡信息长度低位
                                JSON_ID_CARD_CR = data.substring(12, 14);  //返回数据检验位

//                                        Log.i("TAG", "PH：" + PH + "PL:" + PL);
                                //转为10进制后计算
                                int ph = (int) Long.parseLong(PH2, 16) * 0x100;
                                int pl = (int) Long.parseLong(PL2, 16);

//                                        Log.i("TAG", "    111   :" + RxHexTool.hexToDecimal(PH) + "222222   :" + ph + "     333333333333333    ：" + pl + "  44444444    " + PL);
                                //获取将要返回的JSON信息的字节长度
                                JSON_ID_CARD_LENGTH = ph + pl;
                            } else if (RS.equals(AFS330H_XY_bean.DB_WZDPPXMK)) {
                                deviceCallback.onDeviceError(ERROR_CODE_WZDPPXMK, context.getString(R.string.error_wzdppxmk), "");
                            }
                            break;
                        case AFS330H_XY_bean.instruction7://删除所有项目
                            break;
                    }
                } else {
//                            Log.i("TAG", "这是什么玩意：" + previous_receive);
                    if (previous_receive.equals(AFS330H_XY_bean.instruction3) && isXMDQ) {//读取ID卡返回的json
                        JSON_ID_CARD += data;
                        String cr = RxHexTool.makeCheckSum(JSON_ID_CARD);
//                                Log.i("TAG", "当前长度：" + JSON_ID_CARD.length() / 2 + "计算出的长度：" + JSON_ID_CARD_LENGTH + "计算出的校验位：" + cr);
                        if (JSON_ID_CARD.length() / 2 >= JSON_ID_CARD_LENGTH - 2 &&
                                JSON_ID_CARD.length() / 2 <= JSON_ID_CARD_LENGTH + 2 &&
                                cr.equals(JSON_ID_CARD_CR)) {
//                                    Log.i("TAG", "粘包完成：" + JSON_ID_CARD);
                            //转为json字符串
                            JSON_ID_CARD = RxHexTool.hexStringToString(JSON_ID_CARD);
//                                    Log.i("TAG", "转为JSON字符串:" + JSON_ID_CARD);
                            deviceCallback.onReadIDCompleted(JSON_ID_CARD);
                            isXMDQ = false;
                        }
                    } else if (previous_receive.equals(AFS330H_XY_bean.instruction4) && isDPJC) {//检测毒品返回的json
                        JSON_DPJC += data;
                        String cr = RxHexTool.makeCheckSum(JSON_DPJC);
//                                Log.i("TAG", "当前长度：" + JSON_DPJC.length() / 2 + "计算出的长度：" + JSON_DPJC_LENGTH);
                        if (JSON_DPJC.length() / 2 >= JSON_DPJC_LENGTH - 2 &&
                                JSON_DPJC.length() / 2 <= JSON_DPJC_LENGTH + 2 &&
                                cr.equals(JSON_DPJC_CR)) {
//                                    Log.i("TAG", "粘包完成：" + JSON_DPJC);
                            //转为JSON字符串
                            JSON_DPJC = RxHexTool.hexStringToString(JSON_DPJC);
//                                    Log.i("TAG", "转为JSON字符串:" + JSON_DPJC);
                            deviceCallback.onTestCompleted(JSON_DPJC);
                            isDPJC = false;
                        }
                    } else if (previous_receive.equals(AFS330H_XY_bean.instruction6) && isXMSC) {//删除ID卡返回的剩余ID卡的json
                        JSON_ID_CARD += data;
                        String cr = RxHexTool.makeCheckSum(JSON_ID_CARD);
                        Log.i("TAG", "当前长度：" + JSON_ID_CARD.length() / 2 + "计算出的长度：" + JSON_ID_CARD_LENGTH + "计算出的校验位：" + cr);
                        if (JSON_ID_CARD.length() / 2 >= JSON_ID_CARD_LENGTH - 2 &&
                                JSON_ID_CARD.length() / 2 <= JSON_ID_CARD_LENGTH + 2 &&
                                cr.equals(JSON_ID_CARD_CR)) {
//                                    Log.i("TAG", "粘包完成：" + JSON_ID_CARD);
                            //转为json字符串
                            JSON_ID_CARD = RxHexTool.hexStringToString(JSON_ID_CARD);
//                                    Log.i("TAG", "转为JSON字符串:" + JSON_ID_CARD);
                            deviceCallback.onDeleteDeviceProjectSuccess(JSON_ID_CARD);
                            isXMSC = false;
                        }
                    } else if (previous_receive.equals(AFS330H_XY_bean.instruction5) && isXMJZ) {//加载ID卡成功返回的剩余ID卡的json
                        JSON_ID_CARD += data;
                        String cr = RxHexTool.makeCheckSum(JSON_ID_CARD);
//                                Log.i("TAG", "当前长度：" + JSON_ID_CARD.length() / 2 + "计算出的长度：" + JSON_ID_CARD_LENGTH + "计算出的校验位：" + cr);
                        if (JSON_ID_CARD.length() / 2 >= JSON_ID_CARD_LENGTH - 2 &&
                                JSON_ID_CARD.length() / 2 <= JSON_ID_CARD_LENGTH + 2 &&
                                cr.equals(JSON_ID_CARD_CR)) {
//                                    Log.i("TAG", "粘包完成：" + JSON_ID_CARD);
                            //转为json字符串
                            JSON_ID_CARD = RxHexTool.hexStringToString(JSON_ID_CARD);
//                                    Log.i("TAG", "转为JSON字符串:" + JSON_ID_CARD);
                            deviceCallback.onloadCouldProjectSuccess(JSON_ID_CARD);
                            isXMJZ = false;
                        }
                    } else {
//                                Log.i("TAG", "废弃数据:" + data);
                    }
                }

            }
        });
    }

    /**
     * 打开通知，并发送获取设备信息指令（协议规定，不发送是无法发送其他指令的）
     *
     * @param bleDevice
     * @param deviceCallback
     */
    public void openNotify(BleDevice bleDevice, DeviceCallback deviceCallback) {
        this.deviceCallback = deviceCallback;
        //默认的UUID为破冰2号的
        String serviceUUID = AFS330H_XY_bean.AFS330H_SERVICE_UUID;
        String notifyUUID = AFS330H_XY_bean.AFS330H_CHARACTERISTIC_NOTIFY_UUID;
        if (deviceType == 1) {//二合一
            serviceUUID = AFS330H_XY_bean.PBEHY_SERVICE_UUID;
            notifyUUID = AFS330H_XY_bean.PBEHY_CHARACTERISTIC_NOTIFY_UUID;
        }
        notify(bleDevice, serviceUUID, notifyUUID);
    }

    /**
     * 破冰二合一的设备打开通知，并发送获取设备信息指令（协议规定，不发送是无法发送其他指令的）
     *
     * @param bleDevice
     * @param deviceCallback
     */
    public void openNotifyEHY(BleDevice bleDevice, DeviceCallback deviceCallback) {
        this.deviceCallback = deviceCallback;
        notify(bleDevice, AFS330H_XY_bean.PBEHY_SERVICE_UUID, AFS330H_XY_bean.PBEHY_CHARACTERISTIC_NOTIFY_UUID);
    }

    /**
     * 取消通知订阅
     *
     * @param bleDevice
     * @return
     */
    public boolean stopNotify(BleDevice bleDevice) {
        //默认的UUID为破冰2号的
        String serviceUUID = AFS330H_XY_bean.AFS330H_SERVICE_UUID;
        String notifyUUID = AFS330H_XY_bean.AFS330H_CHARACTERISTIC_NOTIFY_UUID;
        if (deviceType == 1) {//二合一
            serviceUUID = AFS330H_XY_bean.PBEHY_SERVICE_UUID;
            notifyUUID = AFS330H_XY_bean.PBEHY_CHARACTERISTIC_NOTIFY_UUID;
        }
        return BleManager.getInstance().stopNotify(bleDevice, serviceUUID, notifyUUID);
    }

    /**
     * 发送数据
     *
     * @param data
     */
    public void sendData(BleDevice bleDevice, String data) {
//        Log.i("TAG", "将要发送的数据：" + data);
        //默认的UUID为破冰2号的
        String serviceUUID = AFS330H_XY_bean.AFS330H_SERVICE_UUID;
        String writeUUID = AFS330H_XY_bean.AFS330H_CHARACTERISTIC_WRITE_UUID;
        if (deviceType == 1) {//二合一
            serviceUUID = AFS330H_XY_bean.PBEHY_SERVICE_UUID;
            writeUUID = AFS330H_XY_bean.PBEHY_CHARACTERISTIC_WRITE_UUID;
        }
        if (bleDevice != null) {
            BleManager.getInstance().write(bleDevice, serviceUUID, writeUUID,
                    RxHexTool.hexStringToBytes(data), new BleWriteCallback() {
                        @Override
                        public void onWriteSuccess(int current, int total, byte[] justWrite) {
                            // 发送数据到设备成功
//                            deviceCallback.onWriteSuccess(current, total, justWrite);
                        }

                        @Override
                        public void onWriteFailure(BleException exception) {
                            // 发送数据到设备失败
                            deviceCallback.writeFailure(exception);
                        }
                    });
        } else {
            deviceCallback.onDeviceError(ERROR_CODE_SBWLJ, context.getString(R.string.error_sbwlj), "");
        }
    }

    /**
     * 发送大型数据
     *
     * @param bleDevice
     * @param data
     */
    public void sendDataMax(BleDevice bleDevice, String data) {
        //默认的UUID为破冰2号的
        String serviceUUID = AFS330H_XY_bean.AFS330H_SERVICE_UUID;
        String writeUUID = AFS330H_XY_bean.AFS330H_CHARACTERISTIC_WRITE_UUID;
        if (deviceType == 1) {//二合一
            serviceUUID = AFS330H_XY_bean.PBEHY_SERVICE_UUID;
            writeUUID = AFS330H_XY_bean.PBEHY_CHARACTERISTIC_WRITE_UUID;
        }
        if (bleDevice != null) {
            BleManager.getInstance().write(bleDevice, serviceUUID,
                    writeUUID, RxHexTool.hexStringToBytes(data), true, true,
                    30, new BleWriteCallback() {
                        @Override
                        public void onWriteSuccess(int i, int i1, byte[] bytes) {
                            Log.i("TAG", "发送数据到设备成功！,当前第：" + i + "包数据，本次一共" + i1 + "包数据");
                        }

                        @Override
                        public void onWriteFailure(BleException e) {
                            // 发送数据到设备失败
                            deviceCallback.writeFailure(e);
                        }
                    });
        } else {
            deviceCallback.onDeviceError(ERROR_CODE_SBWLJ, context.getString(R.string.error_sbwlj), "");
        }
    }

    /**
     * 设置最大传输单元MTU
     *
     * @param bleDevice 要设置的额设备
     * @param mtu       数值
     * @param callback  回调
     */
    public void setMtu(BleDevice bleDevice, int mtu, BleMtuChangedCallback callback) {
        BleManager.getInstance().setMtu(bleDevice, mtu, callback);
    }

    /**
     * 开始检测    传入已解密好的标曲编号
     *
     * @param bleDevice 设备对象
     * @param code      标曲编号
     */
    public void startTest(BleDevice bleDevice, String code) {
        codeString = code;
        String tm = RxHexTool.str2HexStr(codeString);
        String tmcd = Integer.toHexString(tm.length() / 2).length() >= 2 ? Integer.toHexString(tm.length() / 2) : "0" + Integer.toHexString(tm.length() / 2);
        Log.i("TAG", "截取出来的条码是：" + tm + ",转为16进制的条码字节长度:" + tmcd);
        getAfh330HXyBean().setTmcd(tmcd);
        getAfh330HXyBean().setTm(tm);
        sendData(bleDevice, RxHexTool.rightFillMethodSumBleData(getAfh330HXyBean().getInstruction4()));
    }


    /**
     * 开始检测（传入条码）
     *
     * @param bleDevice
     */
    public void startTestBarCode(BleDevice bleDevice, String barcode) {
        if (!TextUtils.isEmpty(barcode)) {
            codeString = barcode.substring(0, 5);
            String tm = RxHexTool.str2HexStr(codeString);
            String tmcd = Integer.toHexString(tm.length() / 2).length() >= 2 ? Integer.toHexString(tm.length() / 2) : "0" + Integer.toHexString(tm.length() / 2);
            Log.i("TAG", "截取出来的条码是：" + tm + ",转为16进制的条码字节长度:" + tmcd);
            getAfh330HXyBean().setTmcd(tmcd);
            getAfh330HXyBean().setTm(tm);
            sendData(bleDevice, RxHexTool.rightFillMethodSumBleData(getAfh330HXyBean().getInstruction4()));
        } else {
            deviceCallback.onDeviceError(ERROR_CODE_SJTMBZQ, context.getString(R.string.error_sjtmbzq), "");
        }
    }

    /**
     * 开始检测（传入加密后的二维码内容）
     *
     * @param bleDevice
     */
    public void startTestQrCode(BleDevice bleDevice, String qrCode) {
        String s = null;
        try {
            s = CalculateCodeUtils.getInstance().calculateCode(qrCode.trim());
        } catch (Exception e) {
            e.printStackTrace();
            Log.i("TAG", "处理出错11111：" + e.toString());
            deviceCallback.onDeviceError(ERROR_CODE_SJTMBZQ, context.getString(R.string.error_sjtmbzq), "");
        }
        Log.i("TAG", "处理完的码2222" + s);
        if (s != null && s.length() == 9) {
            codeString = s.substring(0, 5);
            String tm = RxHexTool.str2HexStr(codeString);
            String tmcd = Integer.toHexString(tm.length() / 2).length() >= 2 ? Integer.toHexString(tm.length() / 2) : "0" + Integer.toHexString(tm.length() / 2);
//            Log.i("TAG", "截取出来的条码是：" + tm + ",转为16进制的条码字节长度:" + tmcd);
            getAfh330HXyBean().setTmcd(tmcd);
            getAfh330HXyBean().setTm(tm);
            getAfh330HXyBean().setSfjcsjkzt("0A");
            sendData(bleDevice, RxHexTool.rightFillMethodSumBleData(getAfh330HXyBean().getInstruction4()));
        } else {
            Log.i("TAG", "处理出错22222：");
            deviceCallback.onDeviceError(ERROR_CODE_SJTMBZQ, context.getString(R.string.error_sjtmbzq), "");
        }

    }


    /**
     * 读取设备项目
     *
     * @param bleDevice 当前已连接设备
     * @param isFGZJXM  是否覆盖最旧项目
     */
    public void readDeviceProject(BleDevice bleDevice, boolean isFGZJXM) {
        getAfh330HXyBean().setSffgzjxm(isFGZJXM == true ? "01" : "00");
        //发送读取ID指令
        sendData(bleDevice, RxHexTool.rightFillMethodSumBleData(getAfh330HXyBean().getInstruction3()));
    }

    /**
     * 加载云端项目
     *
     * @param bleDevice   当前已连接设备
     * @param isFGZJXM    是否覆盖最旧项目
     * @param projectData 项目标曲数据
     */
    public void loadCloudProject(BleDevice bleDevice, boolean isFGZJXM, String projectData) {
        getAfh330HXyBean().setSffgzjxm(isFGZJXM == true ? "01" : "00");
        //发送加载云端项目的指令
        sendData(bleDevice, RxHexTool.rightFillMethodSumBleData(getAfh330HXyBean().getInstruction5()));
        //发送云端项目数据
        sendDataMax(bleDevice, projectData);
    }

    /**
     * 删除设备项目
     *
     * @param bleDevice 当前已连接设备
     * @param barCode   要删除的项目条码
     */
    public void deleteDeviceProject(BleDevice bleDevice, String barCode) {
        if (!TextUtils.isEmpty(barCode)) {
            String tm = RxHexTool.str2HexStr(barCode);
            String tmcd = Integer.toHexString(tm.length() / 2).length() >= 2 ? Integer.toHexString(tm.length() / 2) : "0" + Integer.toHexString(tm.length() / 2);
//            Log.i("TAG", "截取出来的条码是：" + tm + ",转为16进制的条码字节长度:" + tmcd);
            sendData(bleDevice, RxHexTool.rightFillMethodSumBleData(getAfh330HXyBean().getInstruction6(tmcd, tm)));
        } else {
            deviceCallback.onDeviceError(ERROR_CODE_SJTMBZQ, context.getString(R.string.error_sjtmbzq), "");
        }

    }

    /**
     * 获取设备状态
     *
     * @param bleDevice 当前已连接设备
     * @param isJCSJKZT 是否检测试剂卡状态
     */
    public void getDeviceStatus(BleDevice bleDevice, boolean isJCSJKZT) {
        getAfh330HXyBean().setSfjcsjkzt(isJCSJKZT == true ? "0A" : "01");
        //发送获取设备状态的指令
        sendData(bleDevice, RxHexTool.rightFillMethodSumBleData(getAfh330HXyBean().getInstruction2()));
    }

    /**
     * 断开所有设备
     */
    public void disconnectAllDevice() {
        BleManager.getInstance().disconnectAllDevice();
    }

    /**
     * 退出使用  清理资源
     */
    public void quitApply() {
        BleManager.getInstance().destroy();
    }

    /**
     * 打开蓝牙
     */
    public void openBlue() {
        BleManager.getInstance().enableBluetooth();
    }

    /**
     * 蓝牙是否已打开
     */
    public boolean isBlueEnable() {
        return BleManager.getInstance().isBlueEnable();
    }

    /**
     * 解码Base64编码字符串的字符串
     *
     * @param str 要解码的字符串
     * @return 解码完毕的字符串
     */
    public String base64Decode(String str) throws Exception {
        return new String(EncodeUtils.base64Decode(str), "GB2312");
    }
}
